package cmd

import (
	"github.com/go-kratos/kratos/contrib/registry/nacos/v2"
	"github.com/go-kratos/kratos/v2"
	"github.com/go-kratos/kratos/v2/log"
	"github.com/go-kratos/kratos/v2/middleware/tracing"
	"github.com/go-kratos/kratos/v2/transport/grpc"
	"github.com/spf13/cobra"
	_ "go.uber.org/automaxprocs"
	"hello-kratos/kratos-server/internal/conf"
	"hello-kratos/kratos-server/pkg"
	"os"
)

func newApp(logger log.Logger, app *conf.Application, gs *grpc.Server, r *nacos.Registry) *kratos.App {
	return kratos.New(
		kratos.ID(app.Id),
		kratos.Name(app.Name),
		kratos.Version(app.Version),
		kratos.Metadata(map[string]string{}),
		kratos.Logger(logger),
		kratos.Server(gs),
		kratos.Registrar(r),
	)
}

func Command() *cobra.Command {
	return &cobra.Command{
		Use: "kratos-server",
		Run: func(c *cobra.Command, args []string) {
			// 加载配置
			bc := pkg.LoadConf("configs")
			logger := log.With(log.NewStdLogger(os.Stdout),
				"ts", log.DefaultTimestamp,
				"caller", log.DefaultCaller,
				"service.id", bc.Application.Id,
				"service.name", bc.Application.Name,
				"service.version", bc.Application.Version,
				"trace.id", tracing.TraceID(),
				"span.id", tracing.SpanID(),
			)
			log.NewHelper(logger).Infof("kratos-server say: %s", bc.Msg)
			app, cleanup, err := wireApp(bc.Server, bc.Application, bc.Data, bc.Nacos.Registry, logger)
			if err != nil {
				panic(err)
			}
			defer cleanup()

			// start and wait for stop signal
			if err = app.Run(); err != nil {
				panic(err)
			}
		},
	}
}
